#!/bin/bash

# 函数：打印帮助信息  
print_help() {  
    echo "Usage: $0 [-h] [-d] [-a]"  
    echo "Options:"  
    echo "  -h     显示帮助信息"  
    echo "  -d     下载QR基础Docker镜像和克隆仓库"  
    echo "  -a     安装所有模块 (Docker, 下载镜像, 克隆仓库)"  
    echo " 不加参数, 则创建QR用户数据目录和下载QR脚本"  
}

# 函数：克隆QuickResearch仓库
git_clone_quick_research() {
    echo "正在克隆QuickResearch仓库..."
    git clone https://gitee.com/mawenke/quick-research.git $HOME/quick-research
    echo "QuickResearch仓库克隆完成。"
}

# 函数：安装Docker
install_docker() {
    # 检测是否已经安装Docker
    if [ -x "$(command -v docker)" ]; then
        echo "Docker已安装。"
    else
        echo "正在安装Docker..."
        cd
        curl -fsSL https://get.docker.com -o get-docker.sh
        sh get-docker.sh
        sudo groupadd docker
        sudo usermod -aG docker $USER
        rm get-docker.sh
        echo "Docker安装完成。请重新登录以使Docker组更改生效。"
    fi
}
set_docker_registry_mirror() {
    echo "配置 Docker 国内镜像源..."
    sudo mkdir -p /etc/docker
    sudo tee /etc/docker/daemon.json <<-'EOF'
{
    "registry-mirrors": [
        "https://docker.1panel.live",
        "https://registry.docker-cn.com",
        "https://mirror.ccs.tencentyun.com",
        "https://hub-mirror.c.163.com"
    ]
}
EOF
    sudo systemctl daemon-reload
    sudo systemctl restart docker
    echo "Docker 国内镜像源设置完成。"
}

# 函数：下载QuickResearch基础系统镜像  
download_qr_image() {  
    echo "正在下载QuickResearch基础系统镜像..."  
    docker pull mawenke/quick-research:ubuntu-1804-base
    docker pull mawenke/quick-research:ubuntu-2004-base
    docker pull mawenke/quick-research:ubuntu-2204-base
    echo "QuickResearch基础系统镜像下载完成。"  
}

# 主函数：处理参数  
process_options() {  
    while getopts ":hda" opt; do  
        case $opt in  
            h)  
                print_help  
                exit 0  
                ;;  
            d)  
                git_clone_quick_research
                download_qr_image
                ;;  
            a)  
                git_clone_quick_research
                install_docker
                set_docker_registry_mirror
                download_qr_image
                ;;  
            \?)  
                echo "Invalid option: -$OPTARG" >&2  
                print_help  
                exit 1  
                ;;  
            :)  
                echo "Option -$OPTARG requires an argument." >&2  
                print_help  
                exit 1  
                ;;  
        esac  
    done  
}

# 处理命令行参数  
process_options "$@"  

echo "脚本执行完成。QuickResearch已自动部署。"

